package service

import (
	"authserver/global"
	"authserver/model"
	"authserver/utils"
	"encoding/json"
	"fmt"
	"github.com/go-auxiliaries/selenium/log"
	"strings"
	"time"

	"github.com/go-auxiliaries/selenium"
	"github.com/go-auxiliaries/selenium/chrome"
)


// 登录

func GetQrcode(shorUrl string) (videoPath string) {

	var (
		err error
		wd  selenium.WebDriver
	)

	if wd != nil {
		wd.Quit()
	}

	if global.ChromeService==nil{
		utils.StartServer()
	}


	// 起新线程在新标签页打开窗口
	// 启动Chrome浏览器
	caps := selenium.Capabilities{
		"browserName": "chrome",
		"goog:loggingPrefs": map[string]string{"performance": "ALL"},
	}

	imagCaps := map[string]interface{}{
		// "profile.managed_default_content_settings.images": 2,
	}
	// homeDir, _ := os.UserHomeDir()
	dirPath :=   "\\AppData\\Local\\Google\\Chrome\\User Data"
	chromeCaps := chrome.Capabilities{
		Prefs: imagCaps,
		Path:  "Chrome/Application/chrome.exe",
		Args: []string{
			"--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7", // 模拟user-agent，防反爬
			"--user-data-dir=" + dirPath,
		},
	}
	caps.AddChrome(chromeCaps)

	wd, err = selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d/wd/hub", global.ChromePort))
	if err != nil {
		fmt.Println("err3-- ", err.Error())
		return
	}
	// 打开网页
	err = wd.Get(shorUrl)
	if err != nil {
		fmt.Println("err1-- ", err.Error())
		return
	}

	// 等待页面加载完成
	err = wd.WaitWithTimeout(func(wd selenium.WebDriver) (bool, error) {
		state, err := wd.ExecuteScript("return document.readyState", nil)
		if err != nil {
			return false, err
		}
		if state == "complete" {
			return true, nil
		}
		return false, nil
	}, 3*time.Second)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// 监听，获取视频地址
	//targReqId:=""
	videoUrl :=""
	for {
		time.Sleep(time.Second)
		if wd == nil {
			break
		}

		videoDom,errMsg:=wd.FindElement(selenium.ByCSSSelector,"xg-video-container")
		if errMsg!=nil{
			fmt.Println(errMsg.Error())
		}

		videos,_:=videoDom.FindElements(selenium.ByTagName,"video")

		for _,v:=range videos{
			source,_:=v.FindElement(selenium.ByTagName,"source")
			src,_:=source.GetAttribute("src")
			fmt.Println("source_src:",src)
			videoUrl = src
		}

		if videoUrl==""{
			continue
		}
		fmt.Println(videoUrl)

		wd.Close()
		wd.Quit()
		break
	}

	return  videoUrl

}





// 登录

func GetVideoUrl(shorUrl string) (videoPath string) {

	var (
		err error
		wd  selenium.WebDriver
	)

	if wd != nil {
		wd.Quit()
	}

	if global.ChromeService==nil{
		utils.StartServer()
	}


	// 起新线程在新标签页打开窗口
	// 启动Chrome浏览器
	caps := selenium.Capabilities{
		"browserName": "chrome",
		"goog:loggingPrefs": map[string]string{"performance": "INFO"},
	}




	imagCaps := map[string]interface{}{
		"profile.managed_default_content_settings.images": 1,
	}
	// homeDir, _ := os.UserHomeDir()
	dirPath :=   "\\AppData\\Local\\Google\\Chrome\\User Data"
	chromeCaps := chrome.Capabilities{
		Prefs: imagCaps,
		Path:  "Chrome/Application/chrome.exe",
		Args: []string{
			"--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7", // 模拟user-agent，防反爬
			//"--headless",
			"--user-data-dir=" + dirPath,
		},
	}
	caps.AddChrome(chromeCaps)

	wd, err = selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d/wd/hub", global.ChromePort))
	if err != nil {
		fmt.Println("err3-- ", err.Error())
		return
	}
    defer wd.Quit()
	// 打开网页
	err = wd.Get(shorUrl)
	if err != nil {
		fmt.Println("err1-- ", err.Error())
		return
	}

	// 等待页面加载完成
	err = wd.WaitWithTimeout(func(wd selenium.WebDriver) (bool, error) {
		state, err := wd.ExecuteScript("return document.readyState", nil)
		if err != nil {
			return false, err
		}
		if state == "complete" {
			return true, nil
		}
		return false, nil
	}, 3*time.Second)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// 监听，获取视频地址
	videoUrl:=""
	targReqId:=""
	for {
		time.Sleep(time.Second)
		if wd == nil {
			break
		}

		logs,errMsg:=wd.Log(log.Performance)

		if errMsg != nil {
			fmt.Println("222", errMsg.Error())
			if strings.Contains(errMsg.Error(),"target window already closed"){
                global.GVA_LOG.Error(err.Error())
				break
			}
			continue
		}


		for _,v:=range logs{

			var resp model.NetResp
			errMsg=json.Unmarshal([]byte(v.Message),&resp)
			if errMsg!=nil{
				fmt.Println("333", errMsg.Error())
				continue
			}

			if resp.Message.Method == "Network.requestWillBeSent" {
				if strings.Contains(resp.Message.Params.Request.Url,"https://www.douyin.com/aweme/v1/web/aweme/detail"){
					targReqId = resp.Message.Params.RequestId
				}
			}
		}

		if targReqId==""{
			continue
		}
		fmt.Println(targReqId)
		break
	}

	param:=map[string]interface{}{ "requestId":targReqId }

	res,_:=wd.ExecuteChromeDPCommand("Network.getResponseBody",param)

	version, ok := res.(map[string]interface{})
	if !ok || version == nil {

	}
	respBody:=version["body"]

	videoUrl = respBody.(string)

	return  videoUrl

}


// 登录

func ChromeTest(shorUrl string){

    var (
        err error
        wd  selenium.WebDriver
    )

    if wd != nil {
        wd.Quit()
    }

    if global.ChromeService==nil{
        utils.StartServer()
    }


    // 起新线程在新标签页打开窗口
    // 启动Chrome浏览器
    caps := selenium.Capabilities{
        "browserName": "chrome",
        "goog:loggingPrefs": map[string]string{"performance": "ALL"},
    }


    imagCaps := map[string]interface{}{
        // "profile.managed_default_content_settings.images": 2,
    }
    // homeDir, _ := os.UserHomeDir()
    dirPath :=   "\\AppData\\Local\\Google\\Chrome\\User Data"
    chromeCaps := chrome.Capabilities{
        Prefs: imagCaps,
        Path:  "Chrome/Application/chrome.exe",
        Args: []string{
            "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7", // 模拟user-agent，防反爬
            "--user-data-dir=" + dirPath,
        },
    }
    caps.AddChrome(chromeCaps)

    wd, err = selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d/wd/hub", global.ChromePort))
    if err != nil {
        fmt.Println("err3-- ", err.Error())
        return
    }
    // 打开网页
    err = wd.Get(shorUrl)
    if err != nil {
        fmt.Println("err1-- ", err.Error())
        return
    }

    // 等待页面加载完成
    err = wd.WaitWithTimeout(func(wd selenium.WebDriver) (bool, error) {
        state, err := wd.ExecuteScript("return document.readyState", nil)
        if err != nil {
            return false, err
        }
        if state == "complete" {
            return true, nil
        }
        return false, nil
    }, 3*time.Second)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    time.Sleep(time.Second*30)

    wd.Quit()
    return

}
